"""
景点数据模型
"""
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class Attraction(models.Model):
    """景点模型"""
    CATEGORY_CHOICES = [
        ('cultural', '文化古迹'),
        ('natural', '自然风光'),
        ('modern', '现代建筑'),
        ('food', '美食购物'),
    ]
    
    name = models.CharField(max_length=100, verbose_name='景点名称')
    description = models.TextField(verbose_name='景点描述', blank=True, null=True)
    category = models.CharField(
        max_length=20,
        choices=CATEGORY_CHOICES,
        default='cultural',
        verbose_name='景点分类'
    )
    latitude = models.DecimalField(max_digits=10, decimal_places=6, verbose_name='纬度')
    longitude = models.DecimalField(max_digits=10, decimal_places=6, verbose_name='经度')
    ticket_price = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name='门票价格')
    open_time = models.TimeField(verbose_name='开放时间', null=True, blank=True)
    close_time = models.TimeField(verbose_name='关闭时间', null=True, blank=True)
    visit_time = models.IntegerField(verbose_name='建议游览时间（分钟）', null=True, blank=True)
    popularity = models.IntegerField(default=0, verbose_name='景点热度')
    rating = models.FloatField(default=0, verbose_name='评分')
    address = models.CharField(max_length=200, verbose_name='地址', blank=True, null=True)
    amap_poi_id = models.CharField(max_length=50, verbose_name='高德地图POI ID', blank=True, null=True, db_index=True)
    amap_image_urls = models.JSONField(default=list, verbose_name='高德地图图片URL列表', blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'attractions'
        verbose_name = '景点'
        verbose_name_plural = '景点'
        ordering = ['-popularity', 'name']
        indexes = [
            models.Index(fields=['category', 'rating'], name='attraction_category_rating_idx'),
            models.Index(fields=['latitude', 'longitude'], name='attraction_location_idx'),
            models.Index(fields=['popularity'], name='attraction_popularity_idx'),
            models.Index(fields=['name'], name='attraction_name_idx'),
            models.Index(fields=['ticket_price'], name='attraction_price_idx'),
        ]

    def __str__(self):
        return self.name

    def is_open(self, visit_time):
        """检查景点在指定时间是否开放"""
        if not self.open_time or not self.close_time:
            return True
        return self.open_time <= visit_time <= self.close_time


class AttractionImage(models.Model):
    """景点图片"""
    attraction = models.ForeignKey(
        Attraction,
        on_delete=models.CASCADE,
        related_name='images',
        verbose_name='景点'
    )
    image = models.ImageField(upload_to='attractions/', verbose_name='图片')
    is_primary = models.BooleanField(default=False, verbose_name='是否为主图')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'attraction_images'
        verbose_name = '景点图片'
        verbose_name_plural = '景点图片'
        ordering = ['-is_primary', 'created_at']
        indexes = [
            models.Index(fields=['attraction', 'is_primary']),  # 添加索引用于查询主图
        ]

    def __str__(self):
        return f"{self.attraction.name} - 图片"


class AttractionReview(models.Model):
    """景点评价"""
    attraction = models.ForeignKey(
        Attraction,
        on_delete=models.CASCADE,
        related_name='reviews',
        verbose_name='景点'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='attraction_reviews',
        verbose_name='用户'
    )
    rating = models.IntegerField(verbose_name='评分', choices=[(i, i) for i in range(1, 6)])
    content = models.TextField(verbose_name='评价内容', blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'attraction_reviews'
        verbose_name = '景点评价'
        verbose_name_plural = '景点评价'
        ordering = ['-created_at']
        unique_together = ('attraction', 'user')
        indexes = [
            models.Index(fields=['attraction', 'created_at']),  # 添加索引用于查询评价
            models.Index(fields=['user', 'created_at']),  # 添加索引用于查询用户评价
        ]

    def __str__(self):
        return f"{self.user.username} 对 {self.attraction.name} 的评价"


class AttractionFavorite(models.Model):
    """景点收藏"""
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='favorite_attractions',
        verbose_name='用户'
    )
    attraction = models.ForeignKey(
        Attraction,
        on_delete=models.CASCADE,
        related_name='favorited_by',
        verbose_name='景点'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')

    class Meta:
        db_table = 'attraction_favorites'
        verbose_name = '景点收藏'
        verbose_name_plural = '景点收藏'
        unique_together = ('user', 'attraction')
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'created_at']),  # 添加索引用于查询用户收藏
            models.Index(fields=['attraction', 'created_at']),  # 添加索引用于查询景点收藏数
        ]

    def __str__(self):
        return f"{self.user.username} 收藏了 {self.attraction.name}"
